﻿// ***********************************************************************
// Assembly         : ELS
// Author           : linhvn
// Created          : 10-22-2012
//
// Last Modified By : linhvn
// Last Modified On : 10-22-2012
// ***********************************************************************
// <copyright file="AddEditUserForm.cs" company="">
//     Copyright (c) . All rights reserved.
// </copyright>
// <summary></summary>
// ***********************************************************************
using System;
using System.Windows.Forms;
using System.Net.Mail;
using System.Collections.Generic;
using System.Data;
using System.Text.RegularExpressions;

namespace ELS.User
{
    /// <summary>
    /// Class AddEditUserForm
    /// </summary>
    public partial class AddEditUserForm : MdiChildForm
    {
        /// <summary>
        /// The user controller
        /// </summary>
        UserController userController = new UserController();
        Panel parentPanel;
        TextBox textBox;
        PictureBox pictureBox;
        PermissionController permissionController = new PermissionController();
        GroupController groupController = new GroupController();

        /// <summary>
        /// The is add new user
        /// </summary>
        bool isAddNewUser = false;
        bool isViewInfoUser = false;
        bool isEditUser = false;

        Dictionary<String, int> userGroups;
        Dictionary<String, int> allGroups;        

        /// <summary>
        /// Initializes a new instance of the <see cref="AddEditUserForm" /> class.
        /// </summary>
        public AddEditUserForm(TextBox textBox, PictureBox pictureBox, Panel parentPanel)
        {
            InitializeComponent();

            this.textBox = textBox;
            this.pictureBox = pictureBox;
            this.parentPanel = parentPanel;

            isAddNewUser = true;
            allGroups = groupController.GetAllGroupID();
            groupController.LoadCheckListBox(chkbGroups);            
        }

        public AddEditUserForm(string selectUsername, TextBox textBox, PictureBox pictureBox, Panel parentPanel, int status)
        {
            // TODO: Complete member initialization
            InitializeComponent();
            txtUsername.ReadOnly = true;

            this.textBox = textBox;
            this.pictureBox = pictureBox;
            this.parentPanel = parentPanel;

            isAddNewUser = (status == UserCommon.ADD_NEW_USER);
            isViewInfoUser = (status == UserCommon.VIEW_INFO_USER);
            isEditUser = (status == UserCommon.EDIT_USER);

            if (isViewInfoUser)
            {
                foreach (Control ctl in this.Controls)
                    ctl.Enabled = false;
                btnSave.Visible = false;
                btnClose.Visible = false;
            }
            LoadSelectedUserInfo(selectUsername); 
        }

        /// <summary>
        /// Loads the selectd user info.
        /// </summary>
        /// <param name="selectUsername">The select username.</param>
        private void LoadSelectedUserInfo(string selectUsername)
        {
            User updateUser = userController.GetUserInfoByUsername(selectUsername);
            txtUsername.Text = updateUser.Username;
            txtPassword.Text = updateUser.Password;
            txtConfirmPassword.Text = updateUser.Password;
            txtFullname.Text = updateUser.Fullname;
            txtEmail.Text = updateUser.Email;
            txtPhone.Text = updateUser.Phone;
            txtAddress.Text = updateUser.Address;
            txtOrganization.Text = updateUser.Organization;

            userGroups = groupController.SelectGroupIDByUsername(selectUsername);
            allGroups = groupController.GetAllGroupID();
            bool isBindingCheckListBox = groupController.LoadCheckListBox(chkbGroups);
            if (isBindingCheckListBox)
            {

                int i = 0;
                foreach (KeyValuePair<string, int> pairAll in allGroups)
                {
                    foreach (KeyValuePair<string, int> pairUser in userGroups)
                    {
                        if (pairAll.Value == pairUser.Value)
                        {
                            chkbGroups.SetItemChecked(i, true);
                        }
                    }
                    i++;
                }

            }
        }

        /// <summary>
        /// Closes the current form.
        /// </summary>
        private void CloseCurrentForm()
        {
            try
            {
                foreach (Control ctl in parentPanel.Controls)
                {
                    ctl.Dispose();
                }

                ListUserForm listUserFrm = new ListUserForm(textBox, pictureBox, parentPanel);
                listUserFrm.TopLevel = false;
                listUserFrm.Parent = parentPanel;
                listUserFrm.Visible = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show("AddEditUserForm:CloseCurrentForm- " + ex.ToString());
                return;
            }
        }

        /// <summary>
        /// Handles the KeyPress event of the txtPhone control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="KeyPressEventArgs" /> instance containing the event data.</param>
        private void txtPhone_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (!Char.IsDigit(e.KeyChar) && !Char.IsControl(e.KeyChar))
            {
                e.Handled = true;
            }
        }

        private int getValueFromDictionary(Dictionary<String, int> dictionary, String testString)
        {
            foreach (KeyValuePair<string, int> pair in dictionary)
            {
                if (pair.Key.Equals(testString))
                {
                    return pair.Value;
                }
            }
            return -1;
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void btnSave_Click(object sender, EventArgs e)
        {
            string username = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();
            string confirmPassword = txtConfirmPassword.Text.Trim();
            string fullname = txtFullname.Text.Trim();
            string email = txtEmail.Text.Trim();
            string address = txtAddress.Text.Trim();
            string phone = txtPhone.Text.Trim();
            if (phone == UserCommon.preFixPhoneNumber)
            {
                phone = String.Empty;
            }
            string organization = txtOrganization.Text.Trim();
            List<int> userGroup = new List<int>();
            for (int i = 0; i < chkbGroups.Items.Count; i++)
            {
                if (chkbGroups.GetItemChecked(i))
                {
                    DataRowView a = (DataRowView)chkbGroups.Items[i];

                    string item = chkbGroups.GetItemText(a);
                    userGroup.Add(getValueFromDictionary(allGroups, item));

                }
            }

            bool isValidUsername = username.Length > 0;
            bool isValidPassword = password.Length > 0;
            bool isValidConfirmPassword = confirmPassword.Length > 0;
            bool isValidFullname = fullname.Length > 0;
            bool isValidGroup = chkbGroups.CheckedItems.Count > 0;
            bool isMatchPassword = (password == confirmPassword);
            bool isExistUsername = false;
            bool isAddNewUserSuccess = false;
            bool isUpdateUserSuccess = false;
            bool isValidEmail = IsValidEmailAddress(email);

            string validationText = "";
            int validationStatus = -2;
            if (isValidUsername)
            {
                if (isValidPassword)
                {
                    if (isValidConfirmPassword)
                    {
                        if (isMatchPassword)
                        {
                            if (isValidGroup)
                            {
                                if (isValidFullname)
                                {
                                    if (isValidEmail)
                                    {
                                        // check existence of username
                                        isExistUsername = userController.CheckExistUsername(txtUsername.Text.Trim());

                                        if (isAddNewUser)
                                        {
                                            if (!isExistUsername)
                                            {
                                                User newUser = new User();
                                                newUser.Username = username;
                                                newUser.Password = password;
                                                newUser.Email = email;
                                                newUser.Address = address;
                                                newUser.Fullname = fullname;
                                                newUser.Phone = phone;
                                                newUser.Organization = organization;
                                                newUser.Group = userGroup;

                                                // invoke controller to process add new user
                                                isAddNewUserSuccess = userController.AddNewUser(newUser);
                                                if (isAddNewUserSuccess)
                                                {
                                                    validationText = UserCommon.AddUser_Success;
                                                    validationStatus = 1;
                                                }
                                            }
                                            else
                                            {
                                                validationText = UserCommon.AddUser_ExistUsername;
                                                validationStatus = 0;
                                            }
                                        }
                                        else
                                        {
                                            User editUser = new User();
                                            editUser.UserId = userController.GetUserInfoByUsername(username).UserId;
                                            editUser.Username = username;
                                            editUser.Password = password;
                                            editUser.Email = email;
                                            editUser.Address = address;
                                            editUser.Fullname = fullname;
                                            editUser.Phone = phone;
                                            editUser.Organization = organization;
                                            editUser.Group = userGroup;

                                            // invoke controller to process update user
                                            isUpdateUserSuccess = userController.UpdateUser(editUser);
                                            if (isUpdateUserSuccess)
                                            {
                                                validationText = UserCommon.UpdateUser_Success;
                                                validationStatus = 1;
                                            }
                                        }
                                    }
                                    else
                                    {
                                        validationText = UserCommon.AddUser_DoNotEnterEmail;
                                        validationStatus = 0;
                                    }
                                }
                                else
                                {
                                    validationText = UserCommon.AddUser_DoNotEnterEmail;
                                    validationStatus = 0;
                                }
                            }
                            else
                            {
                                validationText = UserCommon.AddUser_DoNotSelectGroup;
                                validationStatus = 0;
                            }
                        }
                        else
                        {
                            validationText = UserCommon.AddUser_NotMatchPassword;
                            validationStatus = 0;
                        }
                    }
                    else
                    {
                        validationText = UserCommon.AddUser_DoNotEnterConfirmPassword;
                        validationStatus = 0;
                    }
                }
                else
                {
                    validationText = UserCommon.AddUser_DoNotEnterPassword;
                    validationStatus = 0;
                }
            }
            else
            {
                validationText = UserCommon.AddUser_DoNotEnterUsername;
                validationStatus = 0;
            }

            if (validationText.Trim().Length != 0 && validationStatus != -2)
            {
                UserCommon.NotifyOnMainForm(textBox, pictureBox, validationText, validationStatus);
                if (validationStatus == 1)
                {
                    CloseCurrentForm();
                }
            }
        }

        public bool IsValidEmailAddress(string email)
        {
            try
            {
                if (email.Length <= 0)
                    return false;
                else
                {
                    MailAddress ma = new MailAddress(email);
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }


        /// <summary>
        /// Handles the Click event of the btnClose control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        private void btnClose_Click(object sender, EventArgs e)
        {
            CloseCurrentForm();
        }
    }
}
